package com.balance.anole.erp.common.binding;

import java.util.Calendar;
import java.util.Date;

import org.eclipse.core.databinding.observable.Diffs;
import org.eclipse.core.databinding.observable.value.AbstractObservableValue;
import org.eclipse.nebula.widgets.calendarcombo.CalendarCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;

public class CalendarComboObservableValue extends AbstractObservableValue {

	private final CalendarCombo dateTime;

	protected Date oldValue;

	ModifyListener listener = new ModifyListener() {
		public void modifyText(ModifyEvent e) {
			Date newValue = dateTimeToDate();
			fireValueChange(Diffs.createValueDiff(oldValue, newValue));
			oldValue = newValue;
		}

	};

	public CalendarComboObservableValue(final CalendarCombo dateTime) {
		this.dateTime = dateTime;
		this.dateTime.addModifyListener(this.listener);
	}

	@Override
	protected Object doGetValue() {
		return dateTimeToDate();
	}

	@Override
	protected void doSetValue(final Object value) {
		if (value instanceof Date) {
			Date date = (Date) value;
			dateToDateTime(date);
		}
	}

	@Override
	public Object getValueType() {
		return Date.class;
	}

	private void dateToDateTime(final Date date) {
		if (!this.dateTime.isDisposed()) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			this.dateTime.setDate(cal);
		}
	}

	private Date dateTimeToDate() {
		Date result = null;
		if (!this.dateTime.isDisposed() && this.dateTime.getDate() != null) {
			result = this.dateTime.getDate().getTime();
		}
		return result;
	}

	@Override
	public synchronized void dispose() {
		this.dateTime.removeModifyListener(this.listener);
		super.dispose();
	}

}
